using System.Data;
using Front._1117_2;
using MySqlConnector;

namespace Front._1118;

public partial class AddBookF : Form
{
    public AddBookF()
    {
        InitializeComponent();
    }

    private void AddBookF_Load(object sender, EventArgs e)
    {
        //初始化加载
        Init();
    }

    private void Init()
    {
        //加载出版社信息
        GetAllPublishers();
    }

    private void GetAllPublishers()
    {
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=qwert789;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        String sql = "SELECT publisher_id,publisher_name FROM publisher_info;";
        // 创建-对象
        MySqlDataAdapter  mySqlDataAdapter = new MySqlDataAdapter(sql, connection);
        //创建dataset
        DataSet  dataSet = new DataSet();
        //填充数据
        mySqlDataAdapter.Fill(dataSet, "publisher_info");
        if (dataSet.Tables["publisher_info"].Rows.Count > 0)
        {
            DataTable publisherTable = dataSet.Tables["publisher_info"];
            // 插入一行全部
            DataRow row = publisherTable.NewRow();
            row[0]  = "0";
            row[1] = "全部";
            publisherTable.Rows.Add(row);
    
            publisher.DataSource = publisherTable;
            publisher.ValueMember = publisherTable.Columns[0].ColumnName;
            publisher.DisplayMember = publisherTable.Columns[1].ColumnName;
        }
    }

    //保存的方法
    private void button1_Click(object sender, EventArgs e)
    {
        //获取组件的值
        string bookName = this.book_name.Text;
        string isbn = this.isbn.Text;
        //获取所选出版社编号
        int publisherId = this.publisher.SelectedIndex;
        
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=qwert789;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        String sql = "insert  into `book_info`(`isbn`,`book_name`,`author`,`publisher_id`,`publish_date`,`book_category`,`book_price`,`book_pages`,`book_desc`,`book_status`,`shelf_id`,`purchase_date`,`book_version`,`create_time`) values \n(@isbn,@book_name,'刘增杰',@publisher_id,'2021-06-01','计算机科学',59.80,320,'讲解MySQL基础与实战开发',1,1,'2023-01-10','第2版','2025-10-10 10:11:29');";
        using var command = new MySqlCommand(sql, connection);
        //给sql变量提供值
        command.Parameters.AddWithValue("isbn", isbn);
        command.Parameters.AddWithValue("book_name", bookName);
        command.Parameters.AddWithValue("publisher_id", publisherId);
        int count = command.ExecuteNonQuery();
        if (count > 0)
        {
            MessageBox.Show("添加成功");
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        else
        {
            MessageBox.Show("添加失败");
            this.DialogResult = DialogResult.No;
            this.Close();
        }
        
    }
}